package com.imcreator.icchat.ClientThreads;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.locks.LockSupport;
import java.util.stream.Collectors;

import org.jline.utils.InputStreamReader;

import com.imcreator.icchat.Colors;
import com.imcreator.icchat.IcChat;
import com.imcreator.icchat.Methods;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class ReceiveThread extends Thread {

    private Socket socket;
    private Thread mainThread;

    public ReceiveThread(Socket socket, Thread mainThread) {
        this.socket = socket;
        this.mainThread = mainThread;
    }

    public void run() {
        // 接受服务器的信息
        try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            while (IcChat.isConnecting) {
                if (socket.isClosed()) {
                    Methods.printAbove(Methods.changeColor(
                        "与服务器的Socket连接意外中断", 
                        Colors.RED_BOLD));
                    IcChat.isConnecting = false;
                    continue;
                }
                String messString = br.readLine();
                if (messString == null) {
                    continue;
                }
                JSONObject receiveMsg = JSONUtil.parseObj(messString);
                String type = receiveMsg.getStr("type");
                String content = receiveMsg.getStr("content");
                switch (type.toLowerCase()) {
                    case "error":
                        if (content.equalsIgnoreCase("name")) {
                            Methods.printAbove(Methods.changeColor(
                                "目标服务器中存在与你昵称相同的连接，请更改昵称后再尝试连接！", 
                                Colors.YELLOW_BOLD));
                                IcChat.isConnecting = false;
                                LockSupport.unpark(mainThread);
                        } else if (content.equalsIgnoreCase("password")) {
                            Methods.printAbove(Methods.changeColor("密码错误！", Colors.RED_BOLD));
                            if (Integer.parseInt(receiveMsg.getStr("number")) <= 0) {
                                Methods.printAbove(Methods.changeColor(
                                    "密码尝试次数过多，连接失败！", 
                                    Colors.RED_BOLD)
                                    );
                                IcChat.isConnecting = false;
                                IcChat.isPasswording = false;
                                LockSupport.unpark(mainThread);
                                continue;
                            }
                            
                            Methods.printAbove(Methods.changeColor(
                                "剩余输入次数: " + receiveMsg.getStr("number"), 
                                Colors.YELLOW));
                        } else if (content.equalsIgnoreCase("clientoffline")) {
                            Methods.printAbove(Methods.changeColor("目标客户端已离线，发送失败！", Colors.RED_BOLD));
                        } else {
                            Methods.printAbove(Methods.changeColor("服务端发送了一条非法命令，尝试断开连接", Colors.RED_BOLD));
                            IcChat.isConnecting = false;
                        }
                        break;
                    case "require":
                        if (content.equalsIgnoreCase("password")) {
                            IcChat.isPasswording = true;
                            LockSupport.unpark(mainThread);
                        } else {
                            Methods.printAbove(Methods.changeColor("服务端发送了一条非法命令，尝试断开连接", Colors.RED_BOLD));
                            IcChat.isConnecting = false;
                        }
                        break;
                    case "info":
                        if (content.equalsIgnoreCase("verified")) {
                            Methods.printAbove(Methods.changeColor("连接成功！", Colors.GREEN_BOLD));
                            IcChat.isPasswording = false;
                            LockSupport.unpark(mainThread);
                        }
                        else if (content.equalsIgnoreCase("disconnect")) {
                            Methods.printAbove(Methods.changeColor(
                                "断开与服务器(" + IcChat.server.getSocket().getInetAddress() + ")的连接", 
                                Colors.YELLOW_BOLD));
                            IcChat.isConnecting = false;
                            IcChat.server = null;
                        }
                        else if (content.equalsIgnoreCase("kick")) {
                            String reason = receiveMsg.getStr("reason");
                            Methods.printAbove(Methods.changeColor(
                                "服务器(" + IcChat.server.getSocket().getInetAddress() + ")已将你踢出，原因：" + reason, 
                                Colors.YELLOW_BOLD));
                            IcChat.isConnecting = false;
                            IcChat.server = null;
                        }
                        else {
                            Methods.printAbove(Methods.changeColor(
                                "服务端发送了一条非法命令，尝试断开连接", 
                                Colors.RED_BOLD));
                            IcChat.isConnecting = false;
                            IcChat.server = null;
                        }
                        break;
                    case "message":
                        Methods.printAbove(content);
                        break;
                    case "unaccepted":
                        if (content.equalsIgnoreCase("shutdown")) {
                            Methods.printAbove(Methods.changeColor(
                                "目标服务器已关闭，连接失败", 
                                Colors.RED_BOLD));
                            IcChat.isConnecting = false;
                            IcChat.isPasswording = false;
                            IcChat.server = null;
                            LockSupport.unpark(mainThread);
                            if (IcChat.isPasswording) {
                                System.out.print("\n");
                            }
                        }
                        break;
                    case "onlinelist":
                        IcChat.onlinelist = Arrays.stream(content.split(","))
                                  .collect(Collectors.toList());
                        IcChat.dynamicCompleter.setNameList(IcChat.onlinelist);
                        break;
                    default:
                        Methods.printAbove(Methods.changeColor("服务端发送了一条非法命令，尝试断开连接", Colors.RED_BOLD));
                        IcChat.isConnecting = false;
                        break;
                }
            }
            shutdown();
        } catch (IOException e) {
            IcChat.isPasswording = false;
            LockSupport.unpark(mainThread);
            e.printStackTrace();
        }
    }

    private void shutdown() {
        if (socket.isClosed()) {
            return;
        }
        try {
            LockSupport.unpark(mainThread);
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
